package com.tianheng.wanzhou.datacollecting.netty.kongyajiSamsung.client;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianheng.wanzhou.datacollecting.db.entity.MachineList;
import com.tianheng.wanzhou.datacollecting.db.service.IMachineListService;
import com.tianheng.wanzhou.datacollecting.util.StrUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.ReferenceCountUtil;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;


/**
 * @Author: ql
 * @Date: 2020/5/12 14:13
 * @Version 1.0
 */
@Component(value = "kongyajiSamsungClient")
public class MyClient {

    @Autowired
    private ObjectFactory<ClientHandler> factory;
    @Autowired
    IMachineListService machineListService;

    private List<MachineList> machineList = new ArrayList<>();

    private BlockingQueue<String> queue = new LinkedBlockingQueue<>(100);

    //netty组件
    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    Bootstrap bs = new Bootstrap();


    MyClient() {
        bs.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(factory.getObject())
                                .addLast("GatherDecoder", new GatherDecoder());
                    }
                });
    }

    @PostConstruct
    private void postConstruct() {
        QueryWrapper<MachineList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mac_type", 2).eq("status", 1).eq("son_type", "03");
        machineList = machineListService.list(queryWrapper);
//        queue.offer("01031388000780A6");
        queue.offer("01031392002CE17E");
        queue.offer("010313F60004A0BF");
    }


    @Scheduled(cron = "0/3 * * * * ? ")
    public void sendMsg() throws InterruptedException{
        for (MachineList machine : this.machineList) {
//            int queueLength = queue.size();
//            ChannelFuture cf = bs.connect(machine.getMacIp(), machine.getPort()).sync();
//            for (int i = 0; i < queueLength; i++) {
//
//                ByteBuf byteBuf = Unpooled.buffer();
//                byteBuf.retain();
//                String data = queue.poll();
//                queue.offer(data);
//                byte[] bytes = StrUtil.hexStr2Byte(data);
//                byteBuf.writeBytes(bytes);
//                cf.channel().writeAndFlush(byteBuf);
//                ReferenceCountUtil.release(byteBuf);
//                Thread.sleep(1000);
//            }
//            //读03
//            ByteBuf byteBuf = Unpooled.buffer();
//            byte[] bytes0 = StrUtil.hexStr2Byte("01031388000780A6");
//            byteBuf.writeBytes(bytes0);
//            cf.channel().writeAndFlush(byteBuf);
//            Thread.sleep(1000);
            try{
                ChannelFuture cf = bs.connect(machine.getMacIp(), machine.getPort()).sync();

                ByteBuf byteBuf = Unpooled.buffer();
                byteBuf.retain();
                byte[] bytes0 = StrUtil.hexStr2Byte("01031392002CE17E");
                byteBuf.writeBytes(bytes0);
                cf.channel().writeAndFlush(byteBuf);
                ReferenceCountUtil.release(byteBuf);
                Thread.sleep(1000);
                //第2次
                ByteBuf byteBuf1 = Unpooled.buffer();
                byteBuf1.retain();
                byte[] bytes1 = StrUtil.hexStr2Byte("010313F60004A0BF");
                byteBuf1.writeBytes(bytes1);
                cf.channel().writeAndFlush(byteBuf1);
                ReferenceCountUtil.release(byteBuf1);
//                Thread.sleep(1000);
            }catch (Exception e){
                System.err.println(machine.getMacIp()+"连接失败" + e.getMessage());
            }



        }
    }

    //隔一小时更新一次设备列表
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void updateMacList() {
        QueryWrapper<MachineList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mac_type", 2).eq("status", 1).eq("son_type", "03");
        machineList = machineListService.list(queryWrapper);
    }
}
